package com.chucang.shucang.gateway.filter;

import com.chucang.shucang.common.base.constant.CommonConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/14 20:25
 * @description 网关全局过滤器
 */
public class RequestGlobalFilter implements GlobalFilter, Ordered {
    private static final String PATH = "/";

    /**
     * 清洗from头 此头只允许内部请求加
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
            httpHeaders.remove(CommonConstant.FROM);
            httpHeaders.put(CommonConstant.REQUEST_START_TIME,
                    Collections.singletonList(String.valueOf(System.currentTimeMillis())));
        }).build();

        addOriginalRequestUrl(exchange, request.getURI());
        String rawPath = request.getURI().getRawPath();
        String newPath = PATH + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, PATH)).skip(1L)
                .collect(Collectors.joining("/"));

        ServerHttpRequest newRequest = request
                .mutate()
                .path(newPath)
                .build();
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

        return chain.filter(exchange
                .mutate()
                .request(newRequest
                        .mutate()
                        .build()
                )
                .build()
        );
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
